package mo.offer_special;

import mo.common.TreeNode;

import java.util.*;

public class L048 {

    private StringBuilder builder = new StringBuilder();

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        builder.setLength(0);
        doSerialize(root);
        return builder.toString();
    }

    private void doSerialize(TreeNode node) {
        if (node == null) {
            builder.append("None,");
        } else {
            builder.append(node.val).append( ",");
            doSerialize(node.left);
            doSerialize(node.right);
        }
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] dataArray = data.split(",");
        List<String> values = new LinkedList<>(Arrays.asList(dataArray));
        return doDeserialize(values);
    }

    private TreeNode doDeserialize(List<String> values) {
        if (values.get(0).equals("None")) {
            values.remove(0);
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(values.get(0)));
        values.remove(0);
        root.left = doDeserialize(values);
        root.right = doDeserialize(values);
        return root;
    }


}
